import * as React from 'react'
import {useState,useEffect} from 'react'
import './Created.css'
import DownLoadPng from '../assets/icons/download.png'
import { useNavigate,useLocation  } from 'react-router-dom';
import Header from '../components/header.jsx'
function Created() {
  const navigateTo = useNavigate();
  const [imageUrl, setImageUrl] = useState('');
  let location = useLocation();  
  // hook API
  useEffect(() => {  
    // 组件挂载后执行的函数  
    let { search } = location;
    // 解析查询参数  
    // let imageUrl = params.get('url'); 
    console.log(search,'解析参数')
    let url =search.split('?url=')
    // console.log(url,'提取的参数')
    setImageUrl(url[1]) 
  }, []); // 传入空数组以确保只在组件首次渲染后执行 
  

  
  async function downloadImage() {
    if (!imageUrl) return;
    try {
      // Fetch the image as a blob
      const response = await fetch(imageUrl);
      const blob = await response.blob();
  
      // Create a link element and set the URL using the blob
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'downloaded-image.jpg'; // 设置下载的文件名
  
      // Append the link to the body and click it to trigger the download
      document.body.appendChild(link);
      link.click();
  
      // Clean up by removing the link element
      document.body.removeChild(link);
    } catch (error) {
      console.error('Error downloading the image:', error);
    }
  }
  const goToCreate=()=>{
    navigateTo('/');
  }
  return (
    <div>
      	<Header></Header>
     <div className="container created">
			<div className="resCon">
				<img className="res_img" src={imageUrl} mode=""></img>
			</div>

			<div className="download">
				<img src={DownLoadPng} onClick={downloadImage} mode=""></img>
			</div>
			<div className="bottom_btn">
				<button className="createMore" onClick={goToCreate}>Generate More</button>
				<button className="shareBtn">Share</button>
			</div>
		</div>
    </div>
  );
}

export default Created;
